from app import db
from datetime import datetime
import json

class Exam(db.Model):
    """试卷模型"""
    __tablename__ = 'exams'
    
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(200), nullable=False, comment='试卷标题')
    description = db.Column(db.Text, comment='试卷描述')
    total_score = db.Column(db.Integer, default=100, comment='总分')
    pass_score = db.Column(db.Integer, default=60, comment='及格分数')
    time_limit = db.Column(db.Integer, default=30, comment='考试时长（分钟）')
    question_count = db.Column(db.Integer, default=10, comment='题目数量')
    is_active = db.Column(db.Boolean, default=True, comment='是否激活')
    created_by = db.Column(db.Integer, db.ForeignKey('admins.id'), nullable=False, comment='创建者ID')
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    
    # 关联关系
    exam_questions = db.relationship('ExamQuestion', backref='exam', lazy='dynamic', cascade='all, delete-orphan')
    exam_records = db.relationship('ExamRecord', backref='exam', lazy='dynamic')
    
    def __repr__(self):
        return f'<Exam {self.title}>'
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'title': self.title,
            'description': self.description,
            'total_score': self.total_score,
            'pass_score': self.pass_score,
            'time_limit': self.time_limit,
            'question_count': self.question_count,
            'is_active': self.is_active,
            'created_by': self.created_by,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None
        }
    
    def get_questions(self):
        """获取试卷题目"""
        return self.exam_questions.order_by(ExamQuestion.sort_order).all()
    
    def get_questions_for_exam(self):
        """获取考试用的题目（不包含正确答案）"""
        questions = []
        for eq in self.get_questions():
            question_dict = eq.question.to_dict_for_exam()
            question_dict['exam_question_id'] = eq.id
            question_dict['score'] = eq.score
            questions.append(question_dict)
        return questions

class ExamQuestion(db.Model):
    """试卷题目关联模型"""
    __tablename__ = 'exam_questions'
    
    id = db.Column(db.Integer, primary_key=True)
    exam_id = db.Column(db.Integer, db.ForeignKey('exams.id'), nullable=False, comment='试卷ID')
    question_id = db.Column(db.Integer, db.ForeignKey('questions.id'), nullable=False, comment='题目ID')
    sort_order = db.Column(db.Integer, default=0, comment='题目顺序')
    score = db.Column(db.Integer, default=10, comment='该题分值')
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    
    def __repr__(self):
        return f'<ExamQuestion {self.exam_id}-{self.question_id}>'
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'exam_id': self.exam_id,
            'question_id': self.question_id,
            'sort_order': self.sort_order,
            'score': self.score,
            'created_at': self.created_at.isoformat() if self.created_at else None
        }

class ExamRecord(db.Model):
    """考试记录模型"""
    __tablename__ = 'exam_records'
    
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False, comment='用户ID')
    exam_id = db.Column(db.Integer, db.ForeignKey('exams.id'), nullable=False, comment='试卷ID')
    start_time = db.Column(db.DateTime, nullable=False, comment='开始时间')
    end_time = db.Column(db.DateTime, comment='结束时间')
    score = db.Column(db.Integer, default=0, comment='得分')
    is_passed = db.Column(db.Boolean, default=False, comment='是否通过')
    answers = db.Column(db.JSON, comment='答题记录（JSON格式）')
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    
    # 关联关系
    certificates = db.relationship('Certificate', backref='exam_record', lazy='dynamic')
    
    def __repr__(self):
        return f'<ExamRecord {self.user_id}-{self.exam_id}>'
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'user_id': self.user_id,
            'exam_id': self.exam_id,
            'start_time': self.start_time.isoformat() if self.start_time else None,
            'end_time': self.end_time.isoformat() if self.end_time else None,
            'score': self.score,
            'is_passed': self.is_passed,
            'answers': self.answers,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None
        }
    
    def calculate_score(self):
        """计算得分"""
        if not self.answers:
            return 0
        
        total_score = 0
        for eq in self.exam.exam_questions:
            question = eq.question
            user_answer = self.answers.get(str(question.id))
            
            if user_answer and question.check_answer(user_answer):
                total_score += eq.score
        
        self.score = total_score
        self.is_passed = total_score >= self.exam.pass_score
        return total_score
    
    def finish_exam(self):
        """完成考试"""
        self.end_time = datetime.utcnow()
        self.calculate_score()
        db.session.commit()
        
        # 如果通过考试，自动生成证书
        if self.is_passed:
            from app.models.certificate import Certificate
            certificate = Certificate.query.filter_by(exam_record_id=self.id).first()
            if not certificate:
                # 生成证书
                from app.services.certificate_service import CertificateService
                certificate_service = CertificateService()
                certificate_service.generate_certificate(self)
        
        return self.score 